package com.lagou.homework.controller;

import com.lagou.homework.util.UuidUtil;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: lizequn
 * @time: 2021/7/19 20:32
 * @description:
 */
@Controller
public class PayController {
    // 存放历史订单
    private static final List<String> failList = new ArrayList<>();

    @Autowired
    private AmqpTemplate rabbitTemplate;

    @GetMapping("/index")
    public String index() {

        return "order";
    }

    @GetMapping("/order")
    public void order() {
        String id = UuidUtil.uuid();
        rabbitTemplate.convertAndSend("ex.pay", "rk.key", id);
        System.out.println(id + " 下单成功，等待支付");

    }

    @ResponseBody
    @GetMapping("/pay")
    public String pay() {
        Object o = rabbitTemplate.receiveAndConvert("queue.pay");
        if (o == null) {
            System.out.println("支付队列获取订单为空");
            return "fail";
        } else {
            System.out.println("支付队列获取订单成功");
            return "success";
        }
    }

    @ResponseBody
    @GetMapping("/fail")
    public List<String> fail() {
        String failId;
        do {
            failId = (String) rabbitTemplate.receiveAndConvert("dl.queue.pay");
            if (failId != null && !failList.contains(failId)) {
                failList.add(failId);
            }
        } while (failId != null);

        return failList;
    }
}
